package main

import (
	"fmt"
	"sync"
	"time"
)

var ticket1 = 10

var mut1 sync.Mutex

func main() {
	go saleManager1("张三")
	go saleManager1("李四")
	go saleManager1("王五")
	go saleManager1("瘪三")
	go saleManager1("老狗")
	//多个goroutine使用同一个变量导致数据不一致使得判断出现问题

	time.Sleep(time.Second * 3)
}

func saleManager1(name string) {

	for {
		mut1.Lock()
		if ticket1 > 0 {

			time.Sleep(time.Millisecond)

			fmt.Println(name, "抢了一张票")
			ticket1--
			fmt.Println("剩余票为", ticket1)
		} else {

			fmt.Println("票已经售完")
			break
		}
		mut1.Unlock()
	}
}
